﻿$.fn.extend({
    "initUpload": function (opt) {
        if (typeof opt != "object") {
            alert('参数错误!');
            return;
        }
        var uploadId = $(this).attr("id");
        if (uploadId == null || uploadId == "") {
            //alert("要设定一个id!");
        }
        $.each(uploadTools.getInitOption(uploadId),
            function (key, value) {
                if (opt[key] == null) {
                    opt[key] = value;
                }
            });
        uploadTools.flushOpt(opt);
        uploadTools.initWithLayout(opt);
        uploadTools.initWithDrag(opt);
        uploadTools.initWithSelectFile(opt);
        uploadTools.initWithUpload(opt);
        uploadTools.initWithCleanFile(opt);
        uploadFileList.initFileList(opt);
    }
});
var uploadTools = {
    "getInitOption": function (uploadId) {
        var initOption = {
            "uploadId": uploadId,
            "uploadUrl": "#",
            "selfUploadBtId": "",
            "scheduleStandard": false,
            "autoCommit": false,
            "isHiddenUploadBt": false,
            "isHiddenCleanBt": false,
            "isAutoClean": false,
            "canDrag": true,
            "velocity": 10,
            "fileType": "*",
            "size": "-1",
            "ismultiple": true,
            "filelSavePath": "",
            "beforeUpload": function () { },
            "onUpload": function () { }
        };
        return initOption;
    },
    "initWithUpload": function (opt) {
        var uploadId = opt.uploadId;
        if (!opt.isHiddenUploadBt) {
            $("#" + uploadId + " .uploadBts .uploadFileBt").off();
            $("#" + uploadId + " .uploadBts .uploadFileBt").on("click",
                function () {
                    uploadEvent.uploadFileEvent(opt);
                });
            $("#" + uploadId + " .uploadBts .uploadFileBt i").css("color", "#0099FF");
        }
        if (opt.selfUploadBtId != null && opt.selfUploadBtId != "") {
            if (uploadTools.foundExitById(opt.selfUploadBtId)) {
                $("#" + opt.selfUploadBtId).off();
                $("#" + opt.selfUploadBtId).on("click",
                    function () {
                        uploadEvent.uploadFileEvent(opt);
                    });
            }
        }
    },
    "foundExitById": function (id) {
        return $("#" + id).size() > 0;
    },
    "initWithCleanFile": function (opt) {
        var uploadId = opt.uploadId;
        if (!opt.isHiddenCleanBt) {
            $("#" + uploadId + " .uploadBts .cleanFileBt").off();
            $("#" + uploadId + " .uploadBts .cleanFileBt").on("click",
                function () {
                    uploadEvent.cleanFileEvent(opt);
                });
            $("#" + uploadId + " .uploadBts .cleanFileBt i").css("color", "#0099FF");
        }
    },
    "initWithSelectFile": function (opt) {
        var uploadId = opt.uploadId;
        $("#" + uploadId + " .uploadBts .selectFileBt").off();
        $("#" + uploadId + " .uploadBts .selectFileBt").on("click",
            function () {
                uploadEvent.selectFileEvent(opt);
            });
    },
    "getShowFileType": function (isImg, fileType, fileName, isImgUrl, fileCodeId) {
        var showTypeStr = "<div class='fileType'>" + fileType + "</div> <i class='iconfont icon-wenjian'></i>";
        if (isImg) {
            if (isImgUrl != null && isImgUrl != "null" && isImgUrl != "") {
                showTypeStr = "<img src='" + isImgUrl + "' style='width:50px;height:50px;marign:10px;display:block;'/>";
            }
        }
        var modelStr = "";
        modelStr += "<div class='fileItem'  fileCodeId='" + fileCodeId + "'>";
        modelStr += "<div class='imgShow'>";
        modelStr += showTypeStr;
        modelStr += " </div>";
        modelStr += "<div class='status'>";
        modelStr += "<i class='iconfont icon-shanchu'></i>";
        modelStr += "</div>";
        modelStr += " <div class='fileName'>";
        modelStr += fileName;
        modelStr += "</div>";
        modelStr += " </div>";
        return modelStr;
    },
    "initWithLayout": function (opt) {
        var uploadId = opt.uploadId;
        var btsStr = "";
        btsStr += "<div class='uploadBts'>";
        btsStr += "<div>";
        btsStr += "<div class='selectFileBt'>选择文件</div>";
        btsStr += "</div>";
        if (!opt.isHiddenUploadBt) {
            btsStr += "<div class='uploadFileBt'>";
            btsStr += "<i class='iconfont icon-shangchuan'></i>";
            btsStr += " </div>";
        }
        if (!opt.isHiddenCleanBt) {
            btsStr += "<div class='cleanFileBt'>";
            btsStr += "<i class='iconfont icon-qingchu'></i>";
            btsStr += " </div>";
        }
        btsStr += "</div>";
        $("#" + uploadId).append(btsStr);
        var boxStr = "<div class='box'></div>";
        $("#" + uploadId).append(boxStr);
    },
    "initWithDrag": function (opt) {
        var canDrag = opt.canDrag;
        var uploadId = opt.uploadId;
        if (canDrag) {
            $(document).on({
                dragleave: function (e) {
                    e.preventDefault();
                },
                drop: function (e) {
                    e.preventDefault();
                },
                dragenter: function (e) {
                    e.preventDefault();
                },
                dragover: function (e) {
                    e.preventDefault();
                }
            });
            var box = $("#" + uploadId + " .box").get(0);
            if (box != null) {
                box.addEventListener("drop",
                    function (e) {
                        uploadEvent.dragListingEvent(e, opt);
                    });
            }
        }
    },
    "initWithDeleteFile": function (opt) {
        var uploadId = opt.uploadId;
        $("#" + uploadId + " .fileItem .status i").off();
        $("#" + uploadId + " .fileItem .status i").on("click",
            function () {
                uploadEvent.deleteFileEvent(opt, this);
            })
    },
    "getSuffixNameByFileName": function (fileName) {
        var str = fileName;
        var pos = str.lastIndexOf(".") + 1;
        var lastname = str.substring(pos, str.length);
        return lastname;
    },
    "isInArray": function (strFound, arrays) {
        var ishave = false;
        for (var i = 0; i < arrays.length; i++) {
            if (strFound == arrays[i]) {
                ishave = true;
                break;
            }
        }
        return ishave;
    },
    "fileIsExit": function (file, opt) {
        var fileList = uploadFileList.getFileList(opt);
        var ishave = false;
        for (var i = 0; i < fileList.length; i++) {
            if (fileList[i] != null && fileList[i].name == file.name && fileList[i].size == file.size) {
                ishave = true;
            }
        }
        return ishave;
    },
    "addFileList": function (fileList, opt) {
        var uploadId = opt.uploadId;
        var boxJsObj = $("#uploadbox").get(0);
        var fileListArray = uploadFileList.getFileList(opt);
        var fileNumber = uploadTools.getFileNumber(opt);
        if (fileNumber + fileList.length > opt.maxFileNumber) {
            alert("最多只能上传" + opt.maxFileNumber + "个文件");
            return;
        }
        var imgtest = /image\/(\w)*/;
        var fileTypeArray = opt.fileType;
        var fileSizeLimit = opt.size;
        for (var i = 0; i < fileList.length; i++) {
            if (uploadTools.fileIsExit(fileList[i], opt)) {
                alert("文件（" + fileList[i].name + "）已经存在！");
                continue;
            }
            var fileTypeStr = uploadTools.getSuffixNameByFileName(fileList[i].name);
            if (fileSizeLimit != -1 && fileList[i].size > (fileSizeLimit * 1000)) {
                alert("文件（" + fileList[i].name + "）超出了大小限制！请控制在" + fileSizeLimit + "KB内");
                continue;
            }
            if (fileTypeArray == "*" || uploadTools.isInArray(fileTypeStr, fileTypeArray)) {
                var fileTypeUpcaseStr = fileTypeStr.toUpperCase();
                if (imgtest.test(fileList[i].type)) {
                    var imgUrlStr = "";
                    if (window.createObjectURL != undefined) {
                        imgUrlStr = window.createObjectURL(fileList[i]);
                    } else if (window.URL != undefined) {
                        imgUrlStr = window.URL.createObjectURL(fileList[i]);
                    } else if (window.webkitURL != undefined) {
                        imgUrlStr = window.webkitURL.createObjectURL(fileList[i]);
                    }
                    var fileModel = uploadTools.getShowFileType(true, fileTypeUpcaseStr, fileList[i].name, imgUrlStr, fileListArray.length);
                    $(boxJsObj).append(fileModel);
                } else {
                    var fileModel = uploadTools.getShowFileType(true, fileTypeUpcaseStr, fileList[i].name, null, fileListArray.length);
                    $(boxJsObj).append(fileModel);
                }
                uploadTools.initWithDeleteFile(opt);
                fileListArray[fileListArray.length] = fileList[i];
            } else {
                alert("不支持该格式文件上传:" + fileList[i].name);
            }
        }
        uploadFileList.setFileList(fileListArray, opt);
    },
    "cleanFilInputWithSelectFile": function (opt) {
        var uploadId = opt.uploadId;
        $("#" + uploadId + "_file").remove();
    },
    "uploadError": function (opt) {
        var uploadId = opt.uploadId;
        $("#" + uploadId + " .box .fileItem .status>i").addClass("iconfont icon-cha");
        var progressBar = $("#" + uploadId + " .subberProgress .progress>div");
        progressBar.css("width", "0%");
        progressBar.html("0%");
    },
    "uploadSuccess": function (opt) {
        var uploadId = opt.uploadId;
        $("#" + uploadId + " .box .fileItem .status>i").off();
        $("#" + uploadId + " .box .fileItem .status>i").addClass("iconfont icon-gou");
        var progressBar = $("#" + uploadId + " .subberProgress .progress>div");
        progressBar.css("width", "0%");
        progressBar.html("0%");
    },
    "getFilesDataAmount": function (opt) {
        var fileList = uploadFileList.getFileList(opt);
        var summer = 0;
        for (var i = 0; i < fileList.length; i++) {
            var fileItem = fileList[i];
            if (fileItem != null) summer = parseFloat(summer) + fileItem.size;
        }
        return summer;
    },
    "uploadFile": function (opt) {
        var uploadUrl = opt.uploadUrl;
        var fileList = uploadFileList.getFileList(opt);
        var formData = new FormData();
        var fileNumber = uploadTools.getFileNumber(opt);
        if (fileNumber <= 0) {
            alert("没有文件，不支持上传");
            return;
        }
        for (var i = 0; i < fileList.length; i++) {
            if (fileList[i] != null) {
                formData.append("file", fileList[i]);
            }
        }
        if (opt.otherData != null && opt.otherData != "") {
            for (var j = 0; j < opt.otherData.length; j++) {
                formData.append(opt.otherData[j].name, opt.otherData[j].value);
            }
        }
        formData.append("filelSavePath", opt.filelSavePath);
        if (uploadUrl != "#" && uploadUrl != "") {
            uploadTools.disableFileUpload(opt);
            uploadTools.disableCleanFile(opt);
            $.ajax({
                type: "post",
                url: uploadUrl,
                data: formData,
                processData: false,
                contentType: false,
                success: function (data) {
                    uploadTools.initWithCleanFile(opt);
                    setTimeout(function () {
                        opt.onUpload(opt, data)
                    },
                        500);
                    if (opt.isAutoClean) {
                        setTimeout(function () {
                            uploadEvent.cleanFileEvent(opt);
                        },
                            2000);
                    }
                },
                error: function (e) { }
            });
        } else {
            uploadTools.disableFileUpload(opt);
            uploadTools.disableCleanFile(opt);
        }
        if (opt.uploadUrl == "#" || opt.uploadUrl == "") {
            uploadTools.getFileUploadPregressMsg(opt);
        }
    },
    "getFileUploadPregressMsg": function (opt) {
        var uploadId = opt.uploadId;
        $("#" + uploadId + " .box .fileItem .status>i").removeClass();
        if (opt.uploadUrl == "#" || opt.uploadUrl == "") {
            if (opt.velocity == null || opt.velocity == "" || opt.velocity <= 0) {
                opt.velocity = 1;
            }
            var filesDataAmount = uploadTools.getFilesDataAmount(opt);
            var percent = 0;
            var bytesRead = 0;
            var intervalId = setInterval(function () {
                bytesRead += 5000 * parseFloat(opt.velocity);
                if (!opt.scheduleStandard) {
                    percent = bytesRead / filesDataAmount * 100;
                    percent = percent.toFixed(2);
                    if (percent >= 100) {
                        clearInterval(intervalId);
                        percent = 100;
                        uploadTools.initWithCleanFile(opt);
                        uploadTools.uploadSuccess(opt);
                    }
                } else {
                    percent += parseFloat(opt.velocity);
                    if (percent >= 100) {
                        clearInterval(intervalId);
                        percent = 100;
                        uploadTools.initWithCleanFile(opt);
                        uploadTools.uploadSuccess(opt);
                    }
                }
            },
                500);
        }
    },
    "disableFileUpload": function (opt) {
        if (!opt.isHiddenUploadBt) {
            var uploadId = opt.uploadId;
            $("#" + uploadId + " .uploadBts .uploadFileBt").off();
            $("#" + uploadId + " .uploadBts .uploadFileBt i").css("color", "#DDDDDD");
        }
    },
    "disableCleanFile": function (opt) {
        if (!opt.isHiddenCleanBt) {
            var uploadId = opt.uploadId;
            $("#" + uploadId + " .uploadBts .cleanFileBt").off();
            $("#" + uploadId + " .uploadBts .cleanFileBt i").css("color", "#DDDDDD");
        }
    },
    "getFileNumber": function (opt) {
        var number = 0;
        var fileList = uploadFileList.getFileList(opt);
        for (var i = 0; i < fileList.length; i++) {
            if (fileList[i] != null) {
                number++;
            }
        }
        return number;
    },
    "flushOpt": function (opt) {
        var uploadId = opt.uploadId;
        $("#" + uploadId).data("opt", opt);
    },
    "getOpt": function (uploadId) {
        var opt = $("#" + uploadId).data("opt");
        return opt;
    }
};
var uploadEvent = {
    "dragListingEvent": function (e, opt) {
        e.preventDefault();
        var fileList = e.dataTransfer.files;
        uploadTools.addFileList(fileList, opt);
        if (opt.autoCommit) {
            uploadEvent.uploadFileEvent(opt);
        }
    },
    "deleteFileEvent": function (opt, obj) {
        var fileItem = $(obj).parent().parent();
        var fileCodeId = fileItem.attr("fileCodeId");
        var fileListArray = uploadFileList.getFileList(opt);
        delete fileListArray[fileCodeId];
        uploadFileList.setFileList(fileListArray, opt);
        fileItem.remove();
    },
    "selectFileEvent": function (opt) {
        var uploadId = opt.uploadId;
        var ismultiple = opt.ismultiple;
        var inputObj = document.createElement('input');
        inputObj.setAttribute('id', uploadId + '_file');
        inputObj.setAttribute('type', 'file');
        inputObj.setAttribute("style", 'visibility:hidden');
        if (ismultiple) {
            inputObj.setAttribute("multiple", "multiple");
        }
        $(inputObj).on("change",
            function () {
                uploadEvent.selectFileChangeEvent(this.files, opt);
            });
        document.body.appendChild(inputObj);
        inputObj.click();
    },
    "selectFileChangeEvent": function (files, opt) {
        uploadTools.addFileList(files, opt);
        uploadTools.cleanFilInputWithSelectFile(opt);
        if (opt.autoCommit) {
            uploadEvent.uploadFileEvent(opt);
        }
    },
    "uploadFileEvent": function (opt) {
        uploadTools.flushOpt(opt);
        if (opt.beforeUpload != null && (typeof opt.beforeUpload === "function")) {
            opt.beforeUpload(opt);
        }
        uploadTools.uploadFile(opt);
    },
    "cleanFileEvent": function (opt) {
        var uploadId = opt.uploadId;
        if (opt.showSummerProgress) {
            $("#" + uploadId + " .subberProgress").css("display", "none");
            $("#" + uploadId + " .subberProgress .progress>div").css("width", "0%");
            $("#" + uploadId + " .subberProgress .progress>div").html("0%");
        }
        uploadTools.cleanFilInputWithSelectFile(opt);
        uploadFileList.setFileList([], opt);
        $("#" + uploadId + " .box").html("");
        uploadTools.initWithUpload(opt);
    }
};
var uploadFileList = {
    "initFileList": function (opt) {
        opt.fileList = new Array();
    },
    "getFileList": function (opt) {
        return opt.fileList;
    },
    "setFileList": function (fileList, opt) {
        opt.fileList = fileList;
        uploadTools.flushOpt(opt);
    }
};
var formTake = {
    "getData": function (formId) {
        var formData = {};
        var $form = $("#" + formId);
        var input_doms = $form.find("input[name][ignore!='true'],textarea[name][ignore!='true']");
        var select_doms = $form.find("select[name][ignore!='true']");
        for (var i = 0; i < input_doms.length; i++) {
            var inputItem = input_doms.eq(i);
            var inputName = "";
            if (inputItem.attr("type") == "radio") {
                if (inputItem.is(":checked")) {
                    inputName = inputItem.attr("name");
                    formData[inputName] = $.trim(inputItem.val());
                }
            } else {
                inputName = inputItem.attr("name");
                formData[inputName] = $.trim(inputItem.val());
            }
        }
        for (var j = 0; j < select_doms.length; j++) {
            var selectItem = select_doms.eq(j);
            var selectName = selectItem.attr("name");
            formData[selectName] = $.trim(selectItem.val());
        }
        return formData;
    },
    "getDataWithUploadFile": function (formId) {
        var formData = [];
        var $form = $("#" + formId);
        var input_doms = $form.find("input[name][ignore!='true'],textarea[name][ignore!='true']");
        var select_doms = $form.find("select[name][ignore!='true']");
        for (var i = 0; i < input_doms.length; i++) {
            var inputItem = input_doms.eq(i);
            var inputName = "";
            if (inputItem.attr("type") == "radio") {
                if (inputItem.is(":checked")) {
                    inputName = inputItem.attr("name");
                    formData[formData.length] = {
                        "name": inputName,
                        "value": $.trim(inputItem.val())
                    }
                }
            } else {
                inputName = inputItem.attr("name");
                formData[formData.length] = {
                    "name": inputName,
                    "value": $.trim(inputItem.val())
                }
            }
        }
        for (var j = 0; j < select_doms.length; j++) {
            var selectItem = select_doms.eq(j);
            var selectName = selectItem.attr("name");
            formData[formData.length] = {
                "name": selectName,
                "value": $.trim(selectItem.val())
            }
        }
        return formData;
    }
};